package qeb.handheldmedical.exam;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import qeb.handheldmedical.R;
import qeb.handheldmedical.adapter.LineExamAdapter;
import qeb.handheldmedical.adapter.SlideListView;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.download.Download;
import qeb.handheldmedical.download.DownloadActivity;
import qeb.handheldmedical.download.MyBroadCastReciver;
import qeb.handheldmedical.download.WpsModel;
import qeb.handheldmedical.download.WpsModel.ClassName;
import qeb.handheldmedical.download.WpsModel.OpenMode;
import qeb.handheldmedical.download.WpsModel.PackageName;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.User;
import qeb.handheldmedical.scanner.MipcaActivityCapture;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author 作者(dugaoyi) E-mail:dugaoyi@163.com
 * @version 创建时间：2016年8月30日 上午9:52:27
 * @declaration 在线学习
 */
/**
 * @author Administrator
 *
 */
public class LineExam extends Activity {
	MyBroadCastReciver receiver;
	private final static int DOWNLOAD_GREQUEST_CODE = 99;
	private final static int SCANNIN_GREQUEST_CODE = 1;
	User usr = new User();
	private SlideListView slidelvlearning;
	private LineExamAdapter adapter;
	Button btn_title_back, btn_title_right;
	private JSONArray learningJsonArray;
	private MultiDialog mDialog;
	private static final int UPDATE = 0;
	private LinearLayout layoutContext;
	private String examID = "", examType = "", examTitle = "", studyId = "",
			exType = "", fileName = "";
	private TextView tv_top_title;

	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		usr = (User) getIntent().getSerializableExtra("userinfo");
		setContentView(R.layout.exam_line_list);
		examType = (String) getIntent().getSerializableExtra("examType");

		tv_top_title = (TextView) findViewById(R.id.tv_top_title);
		btn_title_back = (Button) findViewById(R.id.btn_title_back);
		btn_title_back.setOnClickListener(MyOnClickListener);

		btn_title_right = (Button) findViewById(R.id.btn_title_right);
		btn_title_right.setOnClickListener(MyOnClickListener);

		slidelvlearning = (SlideListView) findViewById(R.id.slidelvlearning);
		setTitleText();
		mDialog = new MultiDialog(LineExam.this, MultiDialog.DialogType.WAITING);
		mDialog.setMessage("正在加载，请稍候......");
		mDialog.show();
		new Thread() {

			@Override
			public void run() {
				try {
					getData();
					myHandler.sendEmptyMessage(UPDATE);
				} catch (Exception e) {
					// TODO: handle exception
					Log.v("LineExam", e.toString());
				}
			}
		}.start();

	}

	/**
	 * 设置标题
	 */
	private void setTitleText() {
		// TODO Auto-generated method stub
		if (examType.equals("1")) {
			tv_top_title.setText("面授学习考试");
		} else if (examType.equals("2")) {
			tv_top_title.setText("科室理论考试");
		} else if (examType.equals("3")) {
			tv_top_title.setText("院级理论考试");
		} else if (examType.equals("4")) {
			tv_top_title.setText("专家面授学习");
		} else if (examType.equals("6")) {
			tv_top_title.setText("课件按排");
		} else if (examType.equals("98")) {
			tv_top_title.setText("面授学习签到签退扫描");
		} else {
			tv_top_title.setText("在线学习");
		}
	}

	/**
	 * 绑定数据
	 */
	private void dataBind() {
		if (learningJsonArray != null && learningJsonArray.length() > 0) {

			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}

			// 签到/签退
			if (examType.equals("98")) {
				adapter = new LineExamAdapter(learningJsonArray.length(),
						LineExam.this, learningJsonArray, true, usr.GH);
			} else {
				adapter = new LineExamAdapter(learningJsonArray.length(),
						LineExam.this, learningJsonArray);
			}
			slidelvlearning.setAdapter(adapter);

			slidelvlearning.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					examID = examTitle = studyId = fileName = exType = "";
					Intent intent = null;
					JSONObject xt;
					try {
						xt = learningJsonArray.getJSONObject(position);
						examID = xt.getString("EXAMID");
						examTitle = xt.getString("TITLE");
						studyId = xt.getString("STUDYID");
						fileName = xt.getString("PATH");
						exType = xt.getString("EXAMTYPE");
						String examstate = "0";

						// 只有面授考试才要判断开放　科室理论考试　院级理论考试
						if (examType.equals("1") || examType.equals("2")
								|| examType.equals("3")) {
							// 开放状态 0开放，1未开放
							examstate = xt.getString("EXAMSTATE");

							if (examstate.equals("0")) {

								// examType为空则为学习

								intent = new Intent(
										LineExam.this,
										qeb.handheldmedical.exam.ExamScoresList.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								intent.putExtra("userinfo", usr);
								intent.putExtra("examID", examID);
								intent.putExtra("examTitle", examTitle);
								LineExam.this.getApplicationContext()
										.startActivity(intent);
							} else {
								mDialog = new MultiDialog(LineExam.this,
										MultiDialog.DialogType.ALERT);
								mDialog.setMessage("此试卷未开放！");
								mDialog.show();
							}
						}
						// 专家面授学习
						else if (examType.equals("4")) {
							// 专家面授学习状态 0已学习，1未学习
							String expertState = xt.getString("EXPERTSTATE");
							if (expertState.equals("0")) {
								mDialog = new MultiDialog(LineExam.this,
										MultiDialog.DialogType.ALERT);
								mDialog.setMessage("此课程已完成学习！");
								mDialog.show();
							}
							// 提交完成学习课程
							else {

								if (usr.BQID != null) {
									Map<String, String> map = new HashMap<String, String>();
									map.put("examID", examID);
									map.put("studyID", studyId);
									map.put("userID", usr.GH);
									JSONArray resultJson = WSHelper
											.getWebserviceFun(
													"FinshExpertStudy", map);
									JSONObject rs = resultJson.getJSONObject(0);
									// 提交状态，0成功，1失败
									String state = rs
											.getString("pda_error_state");
									// 显示信息
									Toast tt = Toast.makeText(LineExam.this,
											rs.getString("pda_error_message"),
											Toast.LENGTH_LONG);
									tt.setGravity(Gravity.CENTER, 0, 0);
									tt.show();
									// 更新列表
									if (state.equals("0")) {
										getData();
										dataBind();
									}

								}

							}
						}
						// 面授学习签到签退扫描
						else if (examType.equals("98")) {
							// 调用扫描
							intent = new Intent();
							intent.setClass(LineExam.this,
									MipcaActivityCapture.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivityForResult(intent,
									SCANNIN_GREQUEST_CODE);
						}
						// 课件按排
						else if (examType.equals("6")) {
							mDialog = new MultiDialog(LineExam.this,
									MultiDialog.DialogType.CONFIRM);
							mDialog.setMessage("您是否要下载查看些课件按排！");
							mDialog.setGoButtonText("是");
							mDialog.setbtnCancelText("否");

							// 下载查看
							mDialog.setDialogGoListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									mDialog.cancel();

									// openLineFile(fileName);
									StudyInLine();
								}
							});

							mDialog.show();
						}
						// 在线学习
						else if (examType.equals("")) {
							boolean state = CheckUserIdStudy(examID, usr.GH);
							// 无权限学习
							if (!state) {
								mDialog = new MultiDialog(LineExam.this,
										MultiDialog.DialogType.ALERT);
								mDialog.setMessage("您无权限学习！");
								mDialog.show();
							}
							// 有权限学习
							else {
								mDialog = new MultiDialog(LineExam.this,
										MultiDialog.DialogType.CONFIRM);
								mDialog.setMessage("请选择进入考试/进入学习！");
								mDialog.setGoButtonText("进入学习");
								mDialog.setbtnCancelText("进入考试");
								// 进入考试
								mDialog.setDialogCancelListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										mDialog.cancel();
										ExamInline(examID, examTitle, exType);
									}
								});

								// 进入学习
								mDialog.setDialogGoListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										mDialog.cancel();
										// openLineFile(fileName);
										StudyInLine();
									}
								});

								mDialog.show();
							}
						}
						// 默认考试类型
						else {
							intent = new Intent(
									LineExam.this,
									qeb.handheldmedical.exam.ExamScoresList.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.putExtra("userinfo", usr);
							intent.putExtra("examID", examID);
							intent.putExtra("examTitle", examTitle);
							intent.putExtra("examType", examType);
							LineExam.this.getApplicationContext()
									.startActivity(intent);
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			});
		}
	}

	private void openLineFile(String fileName) {

		Intent intent = new Intent(LineExam.this,
				qeb.handheldmedical.exam.OpenExamFile.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("examTitle", examTitle);
		intent.putExtra("fileName", fileName);
		LineExam.this.getApplicationContext().startActivity(intent);
	}

	/**
	 * 在线学习
	 */
	private void StudyInLine() {
		Toast tt = null;

		String url = "http://61.153.43.244:8989/StudyFile/" + fileName;
		// 无文档
		if (fileName.equals("")) {

			tt = Toast.makeText(LineExam.this, "无文档下载！", Toast.LENGTH_SHORT);
			tt.setGravity(Gravity.CENTER, 0, 0);
			tt.show();

		}
		// 有文档则下载打开
		else {

			Intent intent = new Intent();

			intent.setClass(LineExam.this, DownloadActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("url", url);
			bundle.putString("fileName", fileName);
			bundle.putString("titleName", examTitle);
			intent.putExtras(bundle);
			startActivityForResult(intent, DOWNLOAD_GREQUEST_CODE);

		}

	}

	/**
	 * 在线考试
	 */
	private void ExamInline(String exId, String exTitle, String exType) {
		Intent intent = new Intent(LineExam.this,
				qeb.handheldmedical.exam.ExamScoresList.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("userinfo", usr);
		intent.putExtra("examID", examID);
		intent.putExtra("examTitle", examTitle);
		intent.putExtra("examType", exType);
		LineExam.this.getApplicationContext().startActivity(intent);
	}

	// 扫描回调
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case DOWNLOAD_GREQUEST_CODE:
			// 下载成功
			if (resultCode == RESULT_OK) {
				String dir = Environment.getExternalStorageDirectory() + "/"
						+ "qebdown/" + fileName;
				boolean flag = openFile(dir);
				if (flag == true) {
					Toast.makeText(LineExam.this, " 打开文件成功", 2000).show();
				} else {
					Toast.makeText(LineExam.this, "打开文件失败", 2000).show();
				}
			}
			// 下载失败
			else {
				Toast tt = Toast.makeText(LineExam.this, "无文档下载！",
						Toast.LENGTH_SHORT);
				tt.setGravity(Gravity.CENTER, 0, 0);
				tt.show();
			}
			break;
		case SCANNIN_GREQUEST_CODE:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				// 显示扫描到的内容
				String result = bundle.getString("result");

				Map<String, String> map = new HashMap<String, String>();
				map.put("studyid", studyId);
				map.put("examid", examID);
				map.put("scanid", result);
				map.put("type", "0");
				map.put("userid", usr.GH);
				JSONArray resultJson = WSHelper.getWebserviceFun(
						"SaveStudySign", map);
				try {
					JSONObject rs = resultJson.getJSONObject(0);
					mDialog = new MultiDialog(LineExam.this,
							MultiDialog.DialogType.ALERT);
					mDialog.setMessage(rs.getString("pda_error_message"));
					mDialog.show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					mDialog = new MultiDialog(LineExam.this,
							MultiDialog.DialogType.ALERT);
					mDialog.setMessage(e.getMessage());
					mDialog.show();
				}

			}
			break;
		}
	}

	/**
	 * 通过webservice获取数据
	 */
	private void getData() {
		if (usr.BQID != null) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("studyrange", "0");
			map.put("starttime", "");
			map.put("endtime", "");
			// 面授学习签到签退扫描
			if (examType.equals("98")) {
				map.put("examtype", "1");
			} else {
				map.put("examtype", examType);
			}
			map.put("userid", usr.GH);
			learningJsonArray = WSHelper.getWebserviceFun("GetStudyList", map);
		}
	}

	private OnClickListener MyOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_title_back:// 返回按钮
				// 学习，返回时清空下载文件
				if (examType.equals("")) {
					String path = Environment.getExternalStorageDirectory()
							+ "/qebdown/";
					File file = new File(path);

					Download download = new Download("");
					download.deleteAllFiles(file);
				}
				LineExam.this.finish();
				break;
			case R.id.btn_title_right:// 刷新按钮
				mDialog = new MultiDialog(LineExam.this,
						MultiDialog.DialogType.WAITING);
				mDialog.setMessage("正在加载，请稍候......");
				mDialog.show();
				new Thread() {

					@Override
					public void run() {
						try {
							getData();
							myHandler.sendEmptyMessage(UPDATE);
						} catch (Exception e) {
							// TODO: handle exception
							Log.v("LineExam", e.toString());
						}
					}
				}.start();

				break;
			}
		}
	};

	/**
	 * 以wps打开文档
	 * 
	 * @param 路径
	 * @return
	 */
	boolean openFile(String path) {
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString(WpsModel.OPEN_MODE, OpenMode.READ_ONLY); // 打开模式
		bundle.putBoolean(WpsModel.SEND_CLOSE_BROAD, true); // 关闭时是否发送广播
		bundle.putString(WpsModel.THIRD_PACKAGE, getPackageName()); // 第三方应用的包名，用于对改应用合法性的验证
		bundle.putBoolean(WpsModel.CLEAR_TRACE, true);// 清除打开记录
		// bundle.putBoolean(CLEAR_FILE, true); //关闭后删除打开文件
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setClassName(PackageName.NORMAL, ClassName.NORMAL);

		File file = new File(path);
		if (file == null) {
			System.out.println("文件为空或者不存在");
			return false;
		}

		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		intent.putExtras(bundle);
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			System.out.println("打开wps异常：" + e.toString());
			e.printStackTrace();
			return false;
		}
		return true;
	}

	Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				dataBind();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
			// isRunning=false;
			mDialog.cancel();
		}
	};

	/**
	 * 验证用户是否有权限可以学习
	 * 
	 * @param examId
	 * @param userGh
	 * @return
	 */
	private boolean CheckUserIdStudy(String examId, String userGh) {
		boolean state = false;
		Map<String, String> map = new HashMap<String, String>();
		map.put("examid", examId);
		map.put("userid", userGh);
		JSONArray checkJson = WSHelper
				.getWebserviceFun("CheckUserIdStudy", map);
		if (null != checkJson && checkJson.length() > 0) {
			try {
				JSONObject check = checkJson.getJSONObject(0);
				if (check.getString("pda_error_state").equals("0"))
					state = true;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				state = false;
			}
		}
		return state;
	}
}
